import { Badge, Button, Form, Input, Popconfirm, Table, message } from "antd";
import { useCallback, useEffect, useMemo, useState } from "react";
import './index.css';
import { ColumnsType } from "antd/es/table";
import { useForm } from "antd/es/form/Form";
import { chatroomListServer } from "@/servers/chatroomServer";
import { useNavigate } from "react-router-dom";
import DetailModal from "./detailModal";
import JoinModal from "./joinModal";

interface SearchGroup {
    name: string;
}

interface GroupSearchResult {
    id: number;
    name: string
    type:boolean
    userCount?:number
    createTime: Date;
}

export default function Group() {
    const [groupResult, setGroupResult] = useState<Array<GroupSearchResult>>([]);

    const navigate = useNavigate()

    const [detailModalOpen , setDetailModalOpen] = useState(false)
    const [joinModalOpen , setJoinModalOpen] = useState(false)
    const [chatroom , setChatroom] = useState<number>(0)

    const gotoChat = (chatroomId:number) => {
        navigate('/chat' , {
            state:{
                chatroomId
            }
        })
    }

    const gotoDetail = async (chatroomId:number) => {
        setChatroom(chatroomId)
        setDetailModalOpen(true)
    }


    const columns: ColumnsType<GroupSearchResult> = useMemo(() => [
        {
            title: '名称',
            dataIndex: 'name'
        },
        {
            title: '创建时间',
            dataIndex: 'createTime',
            render: (_, record) => {
                return new Date(record.createTime).toLocaleString()
            }
        },
        {
            title: '类型',
            dataIndex: 'userCount',
            render: (_, record) => (record.type ? <div>群聊</div> : <div>私聊</div> )
        },
        {
            title: '人数',
            dataIndex: 'userCount',
            render: (_, record) => (record.type && <div>{record.userCount}</div> )
        },
        {
            title: '操作',
            render: (_, record) => (
                <div>
                    <Button onClick={()=>gotoChat(record.id)}>聊天</Button>
                    <Button onClick={()=>gotoDetail(record.id)} >详情</Button>
                    {
                        record.type && (
                            <Button 
                                onClick={()=>{
                                    setChatroom(record.id)
                                    setJoinModalOpen(true)
                                }} 
                                type="primary"
                            >
                                邀请
                            </Button>
                        )
                    }
                    
                </div>
            )
        }
    ], []);

    const searchGroup = async (values: SearchGroup) => {
        try{
            const res = await chatroomListServer(values.name || '');

            const { code ,data } = res.data

            if(code === 201 || code === 200) {
                setGroupResult(data.map((item: GroupSearchResult) => {
                    return {
                        ...item,
                        key: item.id
                    }
                }));
            }
        } catch(e: any){
            message.error(e.response?.data?.message || '系统繁忙，请稍后再试');
        }
    };

    const [form ]  = useForm();

    useEffect(() => {
        searchGroup({
            name: form.getFieldValue('name')
        });
    }, []);


    return <div id="group-container">
        <div className="group-form">
            <Form
                form={form}
                onFinish={searchGroup}
                name="search"
                layout='inline'
                colon={false}
            >
                <Form.Item label="名称" name="name">
                    <Input />
                </Form.Item>

                <Form.Item label=" ">
                    <Button type="primary" htmlType="submit">
                        搜索
                    </Button>
                </Form.Item>
            </Form>
        </div>
        <div className="group-table">
            <Table columns={columns} dataSource={groupResult} style={{width: '1000px'}}/>
        </div>
        <DetailModal 
            isOpen={detailModalOpen} 
            chatroomId={chatroom} 
            handleClose={()=>{
                setDetailModalOpen(false)
            }} 
        />
        <JoinModal 
            chatroomId={chatroom} 
            isOpen={joinModalOpen} 
            handleClose={()=>{
                setJoinModalOpen(false)
            }}
        />
    </div>
}
